package com.dvdfe8.crochet.modelo.dao;

import com.dvdfe8.crochet.modelo.entity.Cliente;
import com.dvdfe8.crochet.modelo.entity.Pedido;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ClienteDaoImpl implements ClienteDao {

    @Autowired
    SessionFactory sessionFactory;

    @Override
    @Transactional
    public void crear(Cliente cliente) {
        sessionFactory.getCurrentSession().saveOrUpdate(cliente);
    }

    @Override
    @Transactional
    public List<Cliente> listarTodos() {
        String hql = "from Cliente";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        return query.list();
    }

    @Override
    @Transactional
    public void eliminar(Cliente cliente) {
        sessionFactory.getCurrentSession().delete(cliente);
    }

    @Override
    @Transactional
    public Cliente getClienteById(int id) {
        String hql = "from Cliente where id=" + id;
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        Cliente cl =(Cliente)query.list().get(0);
        Hibernate.initialize(cl.getPedidos());
        return cl;
    }

    @Override
    @Transactional
    public Cliente getClienteByNombre(String nombre) {
        String hql = "from Cliente where nombre=" + nombre;
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        return (Cliente) query.list().get(0);
    }

    
}
